<template>
  <BasicModal
    v-bind="$attrs"
    :title="t('流程图')"
    :showOkBtn="false"
    :cancelText="t('common.closeText')"
    @register="registerModal"
    @cancel="_closeTip"
    :minHeight="200"
    width="80%"
    :destroyOnClose="true"
  >
    <div class="jeesite-bpm-trace">
      <div class="box-model" v-show="false">
        <div class="box-title">
          <span>{{ t('图例') }} :</span>
          <span style="color: #017501">
            <Icon icon="i-ant-design:check-circle-outlined" style="padding: 5px" />
            {{ t('已完成') }}
          </span>
          <span style="color: #e90606">
            <Icon icon="i-ant-design:clock-circle-outlined" style="padding: 5px" />
            {{ t('进行中') }}
          </span>
          <span style="color: #585858">
            <Icon icon="i-ant-design:minus-circle-outlined" style="padding: 5px" />
            {{ t('未执行') }}
          </span>
        </div>
        <div class="box-tool" v-if="message">{{ message }}</div>
        <div ref="navTree" class="box-tool nav-tree" :data-text-main-process="t('主流程')"></div>
        <div ref="bpmnModel" style="overflow: auto" @click="_closeTip"></div>
      </div>
      <div class="box-table">
        <FormGroup>{{ t('流转信息') }}</FormGroup>
        <BasicTable @register="registerTable" >
          <template #expandedRowRender="{ record }">
            <BasicTable 
              :dataSource="record.children || []" 
              :columns="childTableColumns" 
              :pagination="false"
              :showIndexColumn="false" 
            ></BasicTable>
          </template>
        </BasicTable>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'JeeSiteBpmRuntimeTrace',
  inheritAttrs: false,
});
</script>
<script lang="ts" setup>
import { defineComponent, ref, defineProps, toRefs, computed, onUnmounted, watch } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicTable, useTable } from '/@/components/Table';
import { FormGroup } from '/@/components/Form';
import { Icon } from '/@/components/Icon';
import {
  bpmTrace,
  bpmProcDefModel,
  bpmProcInsModel,
  bpmProcInsHistoryModel,
  bpmProcInsTrace,
} from '/@/api/bpm';
import { _showProcessDiagram, _closeTip } from './js/displaymodel.js';
import { InFireNotificationData } from '/@/api/management/inFireNotification';

const { t } = useI18n('bpm.button');

const message = ref();
const historyProcInsId = ref('');
const procInsId = ref('');
const procDefId = ref('');
const tableDataSource = ref<Recordable[]>([]);
const traceName = ref('');
const tableName = ref('');
const navTree = ref();
const bpmnModel = ref();
// 新增控制是否显示最后一行的响应式变量
const traceStatus = ref([]);
const ChildrenDataSource= ref();

// 子表列定义
const childTableColumns = ref([
  {
    title: t('通知人'),
    dataIndex: 'notifierName',
    width: 100,
  },
  {
    title: t('通知情况'),
    dataIndex: 'linkageLevel',
    width: 100,
  },
  {
    title: t('通知内容'),
    dataIndex: 'notifierContent',
    width: 100,
  },
    {
    title: t('通知时间'),
    dataIndex: 'createTime',
    width: 100,
  },
]);

const props = defineProps({
  maintainTaskId: {
    type: String,
    default: '',
  },
});

const MaintainceBpmTaskId = ref('');
const TableDataSource2 = ref('');
const endRowName = ref('');


// 计算属性，根据TableDataSource2.value是否存在来决定数据源
const resolvedDataSource = computed(() => {
  return TableDataSource2.value || tableDataSource.value;
});

const [registerTable, { reload }] = useTable({
  dataSource: resolvedDataSource, // 使用计算属性作为数据源
  columns: [
    {
      title: t('环节名称'),
      dataIndex: 'name',
      width: 150,
      customRender: ({ record }) => {
        return record.name || t('未设置环节名');
      },
    },
    {
      title: t('创建时间'),
      dataIndex: 'createTime',
      width: 100,
    },
    {
      title: t('完成时间'),
      dataIndex: 'endTime',
      width: 100,
    },
    {
      title: t('任务历时'),
      dataIndex: 'durationFormat',
      width: 80,
    },
    {
      title: t('分配人员'),
      dataIndex: 'assigneeInfo',
      width: 150,
    },
    {
      title: t('审批意见'),
      dataIndex: 'comment',
      width: 200,
    },
  ],
  pagination: false,
  bordered: true,
  size: 'small',
  inset: true,
});

function removeDecimalPart(str) {
  // 查找字符串中最后一个 '秒' 字的位置
  const secondsIndex = str.lastIndexOf('秒');
  if (secondsIndex > -1) {
    // 截取 '秒' 字之前的部分
    const beforeSeconds = str.slice(0, secondsIndex);
    // 找到小数点位置
    const dotIndex = beforeSeconds.lastIndexOf('.');
    if (dotIndex > -1) {
      // 去掉小数点及其后面的内容
      return beforeSeconds.slice(0, dotIndex) + '秒';
    }
  }
  return str;
}

async function showProcessDiagram(bizKey) {
  let data: any = {};
  if (historyProcInsId.value && historyProcInsId.value !== '') {
    data = await bpmProcInsHistoryModel({ id: historyProcInsId.value });
    tableDataSource.value = await bpmProcInsTrace({ id: historyProcInsId.value });
    console.log('tableDataSourceHistory:', tableDataSource.value)
    traceName.value =
      (tableDataSource.value[1]?.procIns?.procDef?.id) ||
      (tableDataSource.value[0]?.procIns?.procDef?.id);
    // 获取数组最后一个元素
    const lastItem =
      tableDataSource.value.length > 0
        ? tableDataSource.value[tableDataSource.value.length - 1]
        : null;
    traceStatus.value = lastItem?.status;
  } else if (procInsId.value && procInsId.value !== '') {
    data = await bpmProcInsModel({ id: procInsId.value });
    tableDataSource.value = await bpmProcInsTrace({ id: procInsId.value });
    console.log('tableDataSource:', tableDataSource.value)
    traceName.value =
      (tableDataSource.value[1]?.procIns?.procDef?.id) ||
      (tableDataSource.value[0]?.procIns?.procDef?.id);
    // 获取数组最后一个元素
    const lastItem =
      tableDataSource.value.length > 0
        ? tableDataSource.value[tableDataSource.value.length - 1]
        : null;
    traceStatus.value = lastItem?.status;
  } else if (procDefId.value && procDefId.value !== '') {
    data = await bpmProcDefModel({ id: procDefId.value });
  }
  if (data.message) {
    message.value = data.message;
    return;
  }
  tableDataSource.value.forEach((item) => {
    if (item.durationFormat) {
      // //console.log(item.durationFormat);
    }
  });
  // 根据traceName的值设置tableName
  if (traceName.value && typeof traceName.value === 'string') {
    if (traceName.value.includes('maintenance_process')) {
      tableName.value = '维保工单流程';
    } else if (traceName.value.includes('supervisor_approval_process')) {
      tableName.value = '监督员审批流程';
    } else if (traceName.value.includes('equipment_fire_warning_process')) {
      tableName.value = '设备火情预警流程';
      // 新增逻辑：请求接口InFireNotificationData
      if (bizKey) {
        const res = await InFireNotificationData({ mainId: bizKey });
        ChildrenDataSource.value = res.list || []; // 赋值响应式变量
        // 手动触发主表 reload（若响应式未自动生效）
        console.log('请求接口InFireNotificationData的结果:', ChildrenDataSource.value);
         const sortedChildren = (res.list || []).sort((a, b) => {
        return new Date(a.createTime).getTime() - new Date(b.createTime).getTime();
      });
      ChildrenDataSource.value = sortedChildren;

        // 筛选子表数据并添加到对应的父表记录中
        const noticeData = ChildrenDataSource.value.filter(item => item.linkageLevel.includes('确认'));
        const disposeData = ChildrenDataSource.value.filter(item => item.linkageLevel.includes('处置'));

        const confirmRow = tableDataSource.value.find(item => item.name === '负责人确认收到预警');
        const disposeRow = tableDataSource.value.find(item => item.name === '负责人处置预警');

        if (confirmRow) {
          confirmRow.children = noticeData;
        }
        if (disposeRow) {
          disposeRow.children = disposeData;
        }

        reload(); // 确保主表和子表重新渲染
      }
    } else if (traceName.value.includes('Equipment_Failure_Process')) {
      tableName.value = '设备故障流程';
    } else if (traceName.value.includes('Fire_Hazard_Process')) {
      tableName.value = '消防隐患流程';
    } else if (traceName.value.includes('leave')) {
      tableName.value = '请假流程';
    } else {
      tableName.value = '';
    }
  }

  // 处理任务历时数据
  tableDataSource.value.forEach((item) => {
    if (item.durationFormat) {
      // 如果字符串包含 '毫秒'，将其替换为 '1秒'
      if (item.durationFormat.includes('毫秒')) {
        item.durationFormat = '1秒';
      } else {
        // 去掉小数点及其后面的内容
        item.durationFormat = removeDecimalPart(item.durationFormat);
      }
    }
  });

  //console.log('tableDataSource:', tableDataSource.value);

  // 在表格第一行增加一行xx流程开始
  const nextRowCreateTime =
    tableDataSource.value.length > 0
      ? tableDataSource.value[0].createTime
      : '';
  const startRow = {
    name: `${tableName.value}开始`,
    createTime: nextRowCreateTime,
    endTime: '',
    durationFormat: '',
    assigneeInfo: '',
    comment: '',
  };
  tableDataSource.value.unshift(startRow);


  // 在表格最后一行增加一行xx流程结束（根据条件判断是否添加）
  if (traceStatus.value === '2') {
    const prevRowEndTime =
      tableDataSource.value.length > 0
        ? tableDataSource.value[tableDataSource.value.length - 1].endTime
        : '';
     endRowName.value = `${tableName.value}结束`;
     console.log('endRowName:', endRowName.value)
    const endRow = {
      name: finalEndRowName.value,
      createTime: '',
      endTime: prevRowEndTime,
      durationFormat: '',
      assigneeInfo: '',
      comment: '',
    };
    tableDataSource.value.push(endRow);
  }
  
  _showProcessDiagram(
    data,
    bpmnModel.value,
    navTree.value,
    tableDataSource.value
  );
}

const [registerModal, { setModalProps }] = useModalInner(
  async (data = {}) => {
    setModalProps({ loading: true });
    if (
      !(data.id && data.id !== '') &&
      data.formKey &&
      data.formKey !== '' &&
      data.bizKey &&
      data.bizKey !== ''
    ) {
      const res = await bpmTrace({ formKey: data.formKey, bizKey: data.bizKey });
      data = res.params || {};
    }
    if (data.status === '1') {
      historyProcInsId.value = '';
      procInsId.value = data.id;
    } else {
      historyProcInsId.value = data.id;
      procInsId.value = '';
    }
    procDefId.value = data.procDef?.id;
    // 确保 tableDataSource.value 有数据
    await showProcessDiagram(data.bizKey);

    if (data.formKey === 'Fire_Hazard_Process' && props.maintainTaskId) {
      endRowName.value = '转维保工单'
      console.log('props.maintainTaskId:', props.maintainTaskId,endRowName.value);
      const newRes = await bpmTrace({
        formKey: 'maintenance_process',
        bizKey: props.maintainTaskId,
      });
      //console.log('二次调用 bpmTrace的id 结果:', newRes.bpmProcIns.id);
      // 不更新data变量，避免影响表格数据
      MaintainceBpmTaskId.value = newRes.bpmProcIns.id;

      if (MaintainceBpmTaskId.value) {
        const secondResult = await bpmProcInsTrace({
          id: MaintainceBpmTaskId.value,
        });

        const processedSecondResult = secondResult.map(item => {
            if (item.durationFormat) {
              item.durationFormat = removeDecimalPart(item.durationFormat); // 调用已有函数
            }
            return item;
          });

        //console.log('二次调用 bpmProcInsTrace的结果:', secondResult);
        // 将 secondResult 数组内对象元素转为 Proxy(Object)
        const proxiedSecondResult = secondResult.map((obj) => {
          return new Proxy(obj, {
            get(target, property) {
              return target[property];
            },
            set(target, property, value) {
              target[property] = value;
              return true;
            },
          });
        });
        // 合并数据
        TableDataSource2.value = [...tableDataSource.value, ...proxiedSecondResult];
        //console.log('tableDataSource2:', TableDataSource2.value);
        // 手动触发表格重新渲染
        reload();
      }
    }
    setModalProps({ loading: false });
  }
);
const finalEndRowName = ref('')
// 添加 watch 监听 endRowName 的变化
watch(endRowName, (newValue, oldValue) => {
  console.log('endRowName 发生变化:', oldValue, ' -> ', newValue);
  finalEndRowName.value = newValue;
  if (traceStatus.value === '2') {
    const prevRowEndTime =
      tableDataSource.value.length > 0
        ? tableDataSource.value[tableDataSource.value.length - 1].endTime
        : '';
    const endRow = {
      name: finalEndRowName.value,
      createTime: '',
      endTime: prevRowEndTime,
      durationFormat: '',
      assigneeInfo: '',
      comment: '',
    };
    // 找到 endRow 在 tableDataSource.value 中的位置并更新
    const endRowIndex = tableDataSource.value.findIndex(
      (item) => item.name === (oldValue || '')
    );
    if (endRowIndex > -1) {
      tableDataSource.value[endRowIndex] = endRow;
    } else {
      tableDataSource.value.push(endRow);
    }
  }
});

</script>
<style scoped lang="less">
.jeesite-bpm-trace {
  position: relative;

  .box-model {
    text-align: center; 

    .box-title {
      padding: 5px;
      margin-bottom: 5px;
      font-weight: bold;

      span {
        padding-right: 5px;
      }
    }

    .box-tool {
      margin-top: 20px;
    }

    .nav-tree a {
      white-space: normal;
      word-break: break-all;
    }

    svg {
      display: inline-block;
    }
  }
}
</style>